/*
Copyright (c) 2009, Young Digital Planet SA
All rights reserved.

* Redistribution and use in source and binary forms, with or without 
  modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this 
  list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, 
  this list of conditions and the following disclaimer in the documentation 
  and/or other materials provided with the distribution.
* Neither the name of the Young Digital Planet SA nor the names of its 
  contributors may be used to endorse or promote products derived from this 
  software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
POSSIBILITY OF SUCH DAMAGE.
*/

package pl.ydp.utils
{
	import flash.external.ExternalInterface;
	
	/**
	 * Queue which operates calling link handlers.
	 */
	public class UnknownLinkHandlerQueue
	{
		private static var m_linkHandlers:Array = new Array();			
		
		/**
		 * Adds handler to queue.
		 * @param handler the function which handles calling link. 
		 * This function must accept an String object as its only parameter and must return Boolean.
		 * The String parameter is link which will be processed by this handler, returning value
		 * indicates if link was processed by handler function or not.
		 * @param priority The priority level of the handler. 
		 * The higher the number, the higher the priority. If two or more handlers share the same priority, 
		 * they are processed in the order in which they were added. The default priority is 0.
		 */
		public static function addLinkHandler( handler:Function, priority:int = 0 ):void {
			var index:int = getMaxHandlerIndexForPriority(priority) + 1;
			
			removeLinkHandler(handler);
       	 	m_linkHandlers.push(new HandlerInfo(handler, priority, index));
       	 	sortHandlerList();
		}
		
		/**
		 * Removes given handler function from queue.
		 * @param handler function which will be removed from queue.
		 */
		public static function removeLinkHandler( handler:Function ):void {
			for(var i:uint = 0; i < m_linkHandlers.length; i++) {
				var hi:HandlerInfo = m_linkHandlers[i] as HandlerInfo;
				
            	if(hi.handler == handler)
                	m_linkHandlers.splice(i, 1);
        	}
        	
        	sortHandlerList();
		}
		
		/**
		 * Calls all added handlers to the queue. Handlers all called in order to priority,
		 * or when they share the same priority in order in which they were added to the 
		 * queue. Calling handlers is executing until hanlder returns true value.
		 * @param url parameter which will be passed as parameter of handler function.
		 */
		public static function showURL( url:String ):void {
			for each ( var handlerInfo:Object in m_linkHandlers ) {
				if(handlerInfo.handler(url) == true)
					return;
			}
		}
		
		/**
		 * Registers default handlers. One of default handlers is
		 * calling ExternalInterface's function 'showURL'.
		 */
		public static function registerHandlers():void {
			UnknownLinkHandlerQueue.addLinkHandler( basicUnknownLinkHandler );
		}
		
		private static function basicUnknownLinkHandler( url:String ):Boolean {
			var res:String
			
			try{
				res = ExternalInterface.call( "showURL", url );
				return res == "true";
			}catch(e:Error){
				return false;
			}
			
			return false;
		}
		
		private static function sortHandlerList():void{
			m_linkHandlers.sortOn(["priority", "index"], Array.NUMERIC | Array.DESCENDING );
		}
		
		private static function getMaxHandlerIndexForPriority(priority:int):int{
			var maxIndex:int = -1;
			
			for (var i:int = 0; i < m_linkHandlers.length; i++){
				var hi:HandlerInfo = m_linkHandlers[i] as HandlerInfo;
				if(hi.priority == priority)
					maxIndex = Math.max(maxIndex, hi.index);
			}
			
			return maxIndex;
		}
	}
}

class HandlerInfo{
	
	public var handler:Function;
	public var priority:int;
	public var index:int;
	
	public function HandlerInfo(handler:Function, priority:int, index:int){
		this.handler = handler;
		this.priority = priority;
		this.index = index;
	}
}